const app = getApp();
const {
  upTime
} = require('/util/public')

Page({
  data: {
    yhjid: '',
    productType: '',
    cashSums: '',
    shopids: '',
    fristmoney: '',
    lastmoney: '',
    spxnum: '',
    gzrlist: [],
    couponlistnum: '',
    rentPersonIds: [],
    sname: '',
    gzrshowxinxi: false,
    snum: '',
    haveTogetherPerson: '',
    nowtimeshow: '',
    product_vip: '',
    sfmoney: '',
    zlnum: 1,
    tit: '',
    yj: '',
    province: '',
    address: '',
    phone: '',
    outPrices: '',
    email: '',
    ssname: '',
    sname: '',
    qname: '',
    num5_1: '',
    leaseTerms: '',
    outPrice: '',
    firstMoneynum: '',
    textaddress: false,
    contents: '',
    haveVINNO: '0',
    lqshowings: false,
    chooseid: '',
    choosemoney: '',
    worryMoney: '',
    types: '',
    firstmoney: false,
    showxinxi: false,
    phonenum: '',
    endtimes: '',
    orderId: '',
    htshow: false,
    namee: '',
    hturl: '',
    phonecate: false,
    typeIndex: 0,
    marquee: 0, //每次移动X坐标
    windowWidth: 0, //小程序宽度
    maxScroll: 0, //文本移动至最左侧宽度及文本宽度
    bindKeyInputname: '',
    bindKeyInputnum: '',
    length: "",
    ishow: false,
    items: [{
        name: '父母',
        value: '父母'
      },
      {
        name: '亲属',
        value: '亲属'
      },
    ],
    seleted: "",
    types: [{
      name: '商品签收确认书'
    }, {
      name: '服务函'
    }, {
      name: '租赁事项确认书'
    }, {
      name: '用户授权协议'
    }, {
      name: '用户注册协议'
    }, {
      name: '用户隐私协议'
    }, {
      name: '查询授权书'
    }, {
      name: '担保申请'
    }, {
      name: '仲裁协议'
    }, ],
    spx: "",
    priceshow: '',
    cont: "", //备注
    vinno: "",
    checked: false,
    text: ' 本平台不对18岁以下未成年用户下单！龙井租物不对18岁已下用户提供服务。',
    marqueePace: 0.1, //滚动速度
    marqueeDistance: 10, //初始滚动距离
    marquee_margin: 0,
    size: 13,
    interval: 2 // 时间间隔
  },
  addgzr() {
    my.navigateTo({
      url: '/pages/user/gzrlist/gzrlist?id=' + '1'
    })
  },
  radioChange(e) {
    //console.log('radio发生change事件，携带value值为：', e.detail.value)
    let value = e.detail.value;
    this.setData({
      seleted: value
    })
  },
  switchTerm(datas, leaseTerm) {
    console.log("11111datasdatas", datas)
    if (datas.trem_value == 365) {
      leaseTerm = 12
    } else if (datas.trem_value == 730) {
      leaseTerm = 24
    } else if (datas.trem_value == 180) {
      leaseTerm = 6
    } else if (datas.trem_value == 90) {
      leaseTerm = 3
    } else if (datas.trem_value == 30) {
      leaseTerm = 1
    }
    return leaseTerm;
  },
  showpop() {
    this.setData({
      lqshowings: true
    })
  },
  onPopupCloselq() {
    this.setData({
      lqshowings: false
    })
  },
  showpops() {
    this.setData({
      htshow: true
    })
  },
  onPopupCloselqss() {
    this.setData({
      htshow: false,
      checked: false,
    })
  },
  onPopupCloselqs() {
    this.setData({
      htshow: false
    })
  },
  typeTap(e) {
    this.setData({
      typeIndex: e.target.dataset.index
    })
  },
  calcPrice(data, leaseTerm, firstMoney, inData) {
    console.log("xinxu ", data, leaseTerm, firstMoney, inData)
    let totalPrice = data.money * this.data.zlnum;
    data.totalPrice = totalPrice
    let newLeaseTerm = (leaseTerm - (firstMoney > 0 ? 1 : 0))
    data.newLeaseTerm = newLeaseTerm
    console.log("newLeaseTerm", newLeaseTerm)
    //余数
    let remainPrice = (totalPrice - firstMoney) % newLeaseTerm
    console.log("yushu ", remainPrice)
    data.remainPrice = remainPrice
    let priceEver = (totalPrice - firstMoney - remainPrice) / newLeaseTerm
    data.priceEver = priceEver
    console.log("1111", priceEver)
    data.meiqiPrice = priceEver / 100;

    data.dayRent = (totalPrice / data.trem_value / 100).toFixed(2)

    //前2期或者1期
    data.firstMoney = firstMoney
    data.firstRent = (((firstMoney > 0 ? firstMoney : 0) + priceEver * (inData.firstPayPeriod - (
      this.data.cashSums != '1' && this.data.productType != '5' ? firstMoney > 0 ? 1 : 0 : ''))) / 100).toFixed(2)
    console.log("firstRent", priceEver, firstMoney, inData.firstPayPeriod, this.data.cashSums)
    //尾期租金
    data.lastRent = ((priceEver + remainPrice) / 100).toFixed(2)
    return data
  },
  onLoad(query) {

    app._init_(this)
    //console.log("手机信息", my.getSystemInfoSync())
    var w = my.getSystemInfoSync().windowWidth - 100;
    var str = '本平台不对18岁以下未成年用户下单！龙井租物服务时间：周一至周日9:30～21:30';
    this.setData({
      marquee: w
    });
    const inData = JSON.parse(query.data);
    console.log("++++", inData)
    if (inData.match.value == 1) {
      inData.detail += inData.match.tit.name
    }

    this.data.maxScroll = str.length * 15 - 100;
    this.data.windowWidth = w;
    this.scrolltxt();
    let leaseTerm = this.switchTerm(inData, leaseTerm);

    let productType = inData.productType;

    let timestamp = new Date().getTime()
    const timestamps = +new Date(Number(timestamp));
    const one_day = 86400000; // 24 * 60 * 60 * 1000;
    const addVal = inData.trem_value * one_day + timestamps;

    let times = upTime("%Y.%M.%D", addVal)

    this.setData({
      outPrice: inData.outPrice,
      zlnum: inData.zlnum,
      endtimes: times,
      shopids: inData.id,
      leaseTerm: leaseTerm,
      haveTogetherPerson: inData.otherParam && inData.otherParam.haveTogetherPerson ? inData.otherParam.haveTogetherPerson : '',
      haveVINNO: inData.otherParam && inData.otherParam.haveVINNO ? inData.otherParam.haveVINNO : '',
      productType: productType,
      image: inData.slideshows[0], //商品图片
      spx: inData.smash.value, //碎屏
      worryMoney: inData.worryMoney / 100, //买断尾款
      worryMoneySum: inData.worryMoney / 100 * inData.zlnum, //总买断尾款
      cashSums: (inData.cash * inData.zlnum) / 100,
      firstPayPeriod: inData.firstPayPeriod, // 首付期数
      cashPeriod: inData.cashPeriod, // 押金期数
    })
    console.log("押金", this.data.cashSums)
    let firstMoney = inData.extraInfo && inData.extraInfo.indexOf('firstMoney') != -1 ? JSON.parse(inData.extraInfo).firstMoney * inData.zlnum : 0
    console.log("inData->2222", inData, firstMoney)
    let preDays = inData.extraInfo && inData.extraInfo.indexOf('preDays') != -1 ? JSON.parse(inData.extraInfo).preDays : 0
    if (productType == '5') {
      //15天已结
      let data = inData;
      leaseTerm = leaseTerm * 2
      data.leaseTerm = leaseTerm

      this.calcPrice(data, leaseTerm, firstMoney, inData);
      this.setData(data);

      // 获当前地址
      // app.getLocation()
    } else if (productType == '7') {
      //三期2天一结
      let data = inData;
      //总价
      firstMoney = 0
      leaseTerm = 3
      data.leaseTerm = leaseTerm

      this.calcPrice(data, leaseTerm, firstMoney, inData);

      this.setData(data);

      // 获当前地址
      // app.getLocation()
    } else if (productType == '8' && preDays > 0) {
      //自定义每期天数
      let data = inData;

      const termDays = data.trem_value

      const ys = termDays % preDays;

      leaseTerm = ys > 0 ? parseInt(termDays / preDays) + 1 : parseInt(termDays / preDays)
      data.leaseTerm = leaseTerm

      console.log(leaseTerm, '自定义租期')

      this.calcPrice(data, leaseTerm, firstMoney, inData);

      this.setData(data);
      // 获取当前地址
      // app.getLocation()

    } else if (productType == '9' && preDays > 0) {
      //自定义期数
      let data = inData;
      leaseTerm = preDays

      data.leaseTerm = leaseTerm

      console.log(leaseTerm, '自定义租期')

      this.calcPrice(data, leaseTerm, firstMoney, inData);

      this.setData(data);
      // 获取当前地址
      // app.getLocation()
    } else {
      let data = inData;
      //总价
      this.calcPrice(data, leaseTerm, firstMoney, inData);
      console.log("数据", data)
      this.setData(data);

      // 获当前地址
      // app.getLocation()
    }


  },
  buyOutPeriod() {
    console.log(this.data, 'sd00000')
    my.navigateTo({
      url: '/pages/order/buyOutPeriod/buyOutPeriod?data=' + JSON.stringify(this.data)
    });
  },
  couponuserlist() {
    let e = {}
    e.status = 0,
      e.page = false
    app.order.couponuserlist(e)
      .then(res => {

        if (res.code == '0') {
          let arr = res.data.filter(item => {
            console.log("哟挥拳rs----", item)
            return (item.productId == this.data.shopids || item.productId == '0' && JSON.parse(item.couponJson).type != '6')

          })
          console.log("哟挥拳rs----+++", arr)
          this.setData({
            couponlistnum: arr.length
          })
        }

        // dddddthis.handleChange(4)
      })
  },
  onShow() {
    var that = this;
    let timestamp = new Date().getTime()
    console.log("222", timestamp)
    var times = upTime("%Y.%M.%D", timestamp)

    that.setData({
      nowtimeshow: times
    })
    // that.couponuserlist()
    var pages = getCurrentPages();
    console.log("返回", pages)
    var currPage = pages[pages.length - 1]; //当前页面
    console.log("返回", currPage)
    if (currPage.data.yhjid) {
      that.setData({
        chooseid: currPage.data.yhjid,
        choosemoney: currPage.data.choosemoney,
      })
    }
    if (currPage.data.gzrlist) {

      let arr = []
      currPage.data.gzrlist.forEach(item => {
        //  item.type == 'choosed' ? upTime("%Y-%M-%D", item.expiretime) : '';

        if (item.type == 'choosed') {
          arr.push(item.id)
        }
      })
      console.log("arrarrarrarrarrarr", arr)
      that.setData({
        gzrshowxinxi: true,
        gzrlist: currPage.data.gzrlist,
        rentPersonIds: arr
      })

    }
    that.get_mrg();
    // that.config()
    // var w = my.getSystemInfoSync().windowWidth;
    // //console.log("#$",w)
    // var str = '滚动文本信息';
    // that.setData({
    //   marquee: w
    // });
    // that.data.maxScroll = str.length * 15 + 4;
    // that.data.windowWidth = w;
    // that.scrolltxt();
    // app.other.hetong()
    //   .then(json => {
    //     console.log("!!!", json)
    //     that.setData({
    //       hturl: json.data
    //     })
    //   })

  },
  config() {

    var that = this;
    app.other.config()
      .then(res => {

        for (const key in res.data.data) {
          // console.info("响应码:", key);
          if (res.data.data.hasOwnProperty(key)) {
            const element = res.data.data[key];
            if (element.name == "no_safe_protect") {
              that.setData({
                sfmoney: parseInt(element.content),
                contents: parseInt(element.content)
                // idi: element.content
              })
            } else if (element.name == "product_5_1") {
              that.setData({
                num5_1: parseInt(element.content),
                // idi: element.content
              })
            } else if (element.name == "product_vip_5_1") {
              that.setData({
                product_vip: parseInt(element.content),
                // idi: element.content
              })
            }
          }
        }


      })


  },
  get_mrg() {
    let users = my.getStorageSync({
      key: 'user'
    }).data;


    if (users.idCardUrl != null) {
      let arrs = JSON.parse(users.idCardUrl)
      console.log("2222", users)

      if (arrs.length == '2' || arrs.length == '3') {
        this.setData({
          ishow: true
        })
      } else {
        this.setData({
          ishow: false
        })
      }

    } else {
      this.setData({
        ishow: false
      })
    }
  },

  scrolltxt() {
    var t = this;
    var d = t.data;

    var interval = setInterval(function () {

      var next = d.marquee - 2; //每次移动距离
      if (next < 0 && Math.abs(next) > d.maxScroll) {
        next = d.windowWidth;
        clearInterval(interval);
        t.scrolltxt();
      }
      d.marquee = next;
      t.setData({
        marquee: next,

      });


    }, 80);


  },
  selectCheckeds() {
    this.setData({
      htshow: true,

    })
  },
  selectChecked() {
    if (!this.data.checked) {
      this.setData({
        checked: !this.data.checked,
        htshow: false
      })
    } else {
      this.setData({
        htshow: false
      })
    }

  },


  // 备注
  onNote(e) {
    this.setData({
      cont: e.detail.value
    });
  },
  onVinno(e) {
    this.setData({
      vinno: e.detail.value
    });
  },
  nav_rz() {
    my.navigateTo({
      url: "/pages/user/authentication/authentication",
      success: (res) => {
        //console.log("222", res)
      },
      fail: () => {

      },
      complete: () => {

      }
    });
  },
  // 选择地址
  onAddressSet() {
    if (this.data.btn) {
      return false
    }
    this.setData({
      btn: true
    })
    let getAddress = my.canIUse('getAddress');
    if (getAddress) {
      my.getAddress({
        success: (res) => {
          console.log("@2", res)
          this.setData({
            btn: false,
            textaddress: false,
            tit: res.result.fullname, // 姓名
            province: res.result.prov, // 省
            city: res.result.city, //市
            district: res.result.area, // 区
            street: res.result.street, //路
            address: res.result.address, //地址
            phone: res.result.mobilePhone, //电话
          });
        },
        fail: (e) => {
          console.log("@", e)

          this.setData({
            btn: false,
            textaddress: true
          })
        }
      });
    } else {
      my.alert({
        title: '提示',
        content: '当前支付宝版本过低，无法使用此功能，请升级最新版本支付宝'
      });
    }
  },
  regionPicker() {
    my.regionPicker({
      success: (res) => {
        console.log("111", res)
        this.setData({
          province: res.data[0], // 省
          city: res.data[1], //市
          district: res.data[2],
        })
      },
      fail: (e) => {
        console.log("222", e)
      },
    })
  },
  colseAddress() {
    this.setData({
      tit: null, // 姓名
      province: null, // 省
      city: null, //市
      district: null, // 区
      street: null, //路
      address: null, //地址
      phone: null, //电话
    });
  },

  // 租赁协议
  zulin() {
    let data = new Date()
    data = data.getFullYear() + '年' + (data.getMonth() + 1) + '月' + data.getDate() + '日'
    let item = {
      createtime: data, // 时间
      leaseTerm: Math.floor(this.data.trem_value / 30), // 租期
      allRent: this.data.buyOut / 100, // 总租金
      tit: this.data.tit, //
      phone: this.data.phone,
      shopsVo: this.data.shops,
      userVo: my.getStorageSync({
        key: 'user'
      }).data,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      address: this.data.address,
      params: {
        // 商品基础数据
        title: this.data.msg,
        id: this.data.id,
        model: {
          price: this.data.money,
          leaseTerm: this.data.trem_value,
        },
        deposit: this.data.cash,
        buyOutPrice: this.data.buyOut,
        image: this.data.image,
        detail: this.data.detail,
        smash: this.data.smash.value
      }
    }

    my.navigateTo({
      url: `/pages/user/agreementList/agreementList?param=${encodeURIComponent(JSON.stringify(item))}`
    })
  },
  htbtn() {
    my.downloadFile({
      // 示例 url，并非真实存在
      url: this.data.hturl,
      success({
        apFilePath
      }) {
        my.openDocument({
          filePath: apFilePath,
          fileType: 'pdf',
          success: res => {
            console.log('open document success');
          },
        });
      },
    });
  },
  userCredit() {
    let data = new Date()
    data = data.getFullYear() + '年' + (data.getMonth() + 1) + '月' + data.getDate() + '日'
    let item = {
      createtime: data, // 时间
      leaseTerm: Math.floor(this.data.trem_value / 30), // 租期
      allRent: this.data.buyOut / 100, // 总租金
      tit: this.data.tit, //
      phone: this.data.phone,
      shopsVo: this.data.shops,
      userVo: my.getStorageSync({
        key: 'user'
      }).data,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      address: this.data.address,
      params: {
        // 商品基础数据
        title: this.data.msg,
        id: this.data.id,
        model: {
          price: this.data.money,
          leaseTerm: this.data.trem_value,
        },
        deposit: this.data.cash,
        buyOutPrice: this.data.buyOut,
        image: this.data.image,
        detail: this.data.detail,
        smash: this.data.smash.value
      }
    }

    my.navigateTo({
      url: `/pages/user/userCredit/userCredit?param=${encodeURIComponent(JSON.stringify(item))}`
    })
  },
  assurance() {
    let data = new Date()
    data = data.getFullYear() + '年' + (data.getMonth() + 1) + '月' + data.getDate() + '日'
    let item = {
      createtime: data, // 时间
      leaseTerm: Math.floor(this.data.trem_value / 30), // 租期
      allRent: this.data.buyOut / 100, // 总租金
      tit: this.data.tit, //
      phone: this.data.phone,
      shopsVo: this.data.shops,
      userVo: my.getStorageSync({
        key: 'user'
      }).data,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      address: this.data.address,
      params: {
        // 商品基础数据
        title: this.data.msg,
        id: this.data.id,
        model: {
          price: this.data.money,
          leaseTerm: this.data.trem_value,
        },
        deposit: this.data.cash,
        buyOutPrice: this.data.buyOut,
        image: this.data.image,
        detail: this.data.detail,
        smash: this.data.smash.value
      }
    }

    my.navigateTo({
      url: `/pages/user/assurance/assurance?param=${encodeURIComponent(JSON.stringify(item))}`
    })
  },

  // fromId
  onSubmitfromId(e) {
    console.log("11111", e)
    this.setData({
      formId: e.detail.formId
    })


  },
  choosePhoneContact() {
    my.choosePhoneContact({
      success: (res) => {

        this.setData({
          phonenum: res.mobile,
          namee: res.name,
          showxinxi: true
        })
        // my.alert({
        //   content: 'choosePhoneContact response: ' + JSON.stringify(res)
        // });
      },
      fail: (res) => {
        // my.alert({
        console.log("通讯录sb", res)
        if (res.error == '2001') {
          my.confirm({
            title: '温馨提示',
            content: '确认订单需获取您的紧急联系人，请在授权管理页面打开通讯录授权开关',
            confirmButtonText: '立即开启',
            cancelButtonText: '暂不需要',
            success: (result) => {
              //console.log("2222", result)
              if (result.confirm) {
                my.openSetting({
                  success: (res) => {
                    //console.log("设置",res)
                    if (res.authSetting.contact) {
                      this.setData({
                        phonecate: true
                      })
                    }
                    /*
                     * res.authSetting = {
                     *   "userInfo": true,
                     *   "location": true,
                     *   ...
                     * }
                     */
                  }
                })
              }
            },
          });
        } else if (res.error == '11') {
          my.alert({
            title: '抱歉',
            content: '请选择您的联系人！',
            buttonText: '确定',
            success: () => {

            },
            fail: () => {

            },
            complete: () => {

            }
          });
        } else if (res.error == '10') {
          my.openSetting({
            success: (res) => {
              //console.log("设置",res)
              if (res.authSetting.contact) {
                this.setData({
                  phonecate: true
                })
              }
              /*
               * res.authSetting = {
               *   "userInfo": true,
               *   "location": true,
               *   ...
               * }
               */
            }
          })
        } else if (res.error == '2002') {
          my.openSetting({
            success: (res) => {
              //console.log("设置",res)
              if (res.authSetting.contact) {
                this.setData({
                  phonecate: true
                })
              }
              /*
               * res.authSetting = {
               *   "userInfo": true,
               *   "location": true,
               *   ...
               * }
               */
            }
          })
        }
      }


    });
  },
  addressnum(e) {
    console.log("111", e.detail.value)
    this.setData({
      address: e.detail.value
    })
  },
  phonenum(e) {
    console.log("111", e.detail.value)
    this.setData({
      phone: e.detail.value
    })
  },
  nametit(e) {
    console.log("111", e.detail.value)
    this.setData({
      tit: e.detail.value
    })
  },
  email(e) {
    console.log("111", e.detail.value)
    this.setData({
      email: e.detail.value
    })
  },


  getPhoneNumber() {
    // this.onSubmit()
    // return
    // 没有手机号
    let that = this
    let user = my.getStorageSync({
      key: 'user'
    });
    let phone = user.data.phone ? user.data.phone : ''
    console.log("phonephonephonephone", phone.length)

    if (app.globalData.userlocation == 'null' || app.globalData.userlocation == '用户拒绝访问当前地址') {
      // 获当前地址
      app.getLocation()
      return false;
    }
    if (phone.length != 11) {
      if (user.data.otherAppId != null && user.data.otherAppId) { //第三方
        my.getPhoneNumber({
          protocols: {
            isvAppId: user.data.otherAppId
          },
          success: (res) => {
            console.log("=============支付宝返回==============", res)
            let encryptedData = res.response;
            let data = {
              encryptedData: encryptedData
            }
            app.user.setPhoneNum(data)
              .then((json => {
                console.log("=============后端返回==============", json)
                if (json.code == 200) {
                  user.data.phone = json.data
                  // 保存到缓存中
                  my.setStorage({
                    key: 'user',
                    data: user.data,
                  })
                  that.onSubmit()
                } else {
                  that.onSubmit()
                }
              }))
          },
          fail: (res) => {
            console.log("================支付宝返回2====================", res);
            //console.log('getPhoneNumber_fail');
          },
        });
      } else {
        my.getPhoneNumber({

          success: (res) => {
            console.log("=============支付宝返回==============", res)
            let encryptedData = res.response;
            let data = {
              encryptedData: encryptedData
            }
            app.user.setPhoneNum(data)
              .then((json => {
                console.log("=============后端返回==============", json)
                if (json.code == 200) {
                  user.data.phone = json.data
                  // 保存到缓存中
                  my.setStorage({
                    key: 'user',
                    data: user.data,
                  })
                  that.onSubmit()
                } else {
                  that.onSubmit()
                }
              }))
          },
          fail: (res) => {
            console.log("================支付宝返回2====================", res);
            //console.log('getPhoneNumber_fail');
          },
        });
      };
    } else {
      that.onSubmit()
    }
  },
  bindKeyInput(e) {
    //console.log("eeeeeeeeeeeeee",e)
    this.setData({
      bindKeyInputname: e.detail.value
    })
  },
  bindKeyInputnum(e) {
    //console.log("手机号输入", e)
    this.setData({
      bindKeyInputnum: e.detail.value
    })
  },

  showToast() {
    my.showToast({
      content: '尾期金额不一致是由于补偿余数金额',
      duration: 2000,
    });
  },

  //提交数据
  onSubmit() {
    my.showLoading({
      content: '加载中...'
    });
    setTimeout(() => {
      my.hideLoading();
    }, 100)

    if (!this.data.tit && !this.data.textaddress) {
      this.onAddressSet();
      return;
    }

    if (this.data.textaddress) {
      if (this.data.tit == '') {
        my.showToast({
          type: 'fail',
          content: '请填写您的收货人!',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }
      if (this.data.phone == '') {
        my.showToast({
          type: 'fail',
          content: '请填写您的收货人手机号码!',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }
      const regex = /^1[3456789]\d{9}$/; //使用此正则即可
      if (!regex.test(this.data.phone)) {
        my.showToast({
          type: 'fail',
          content: '请输入正确的手机号码!',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }

      if (this.data.province == '') {
        my.showToast({
          type: 'fail',
          content: '请选择您所在的地区!',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }

      if (this.data.address == '') {
        my.showToast({
          type: 'fail',
          content: '请填写您的详细地址!',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }


    }
    // if (!this.data.email) {
    //   my.showToast({
    //     type: 'fail',
    //     content: '请补全邮箱信息',
    //     duration: 3000,
    //     success: () => {

    //     },
    //   });
    //   return false;
    // }
    // const regyx = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
    // if (!regyx.test(this.data.email)) {
    //   my.showToast({
    //     type: 'fail',
    //     content: '请输入正确的邮箱!',
    //     duration: 3000,
    //     success: () => {

    //     },
    //   });
    //   return false;
    // }
    console.log("666+", !this.data.ishow && (!this.data.msg.includes('免审') || this.data.msg != '金立老人机'))

    if (!this.data.ishow && !this.data.msg.includes('免审') && this.data.msg != '金立老人机') {
      console.log("来了")
      my.showToast({
        type: 'fail',
        content: '请补全身份信息',
        duration: 3000,
        success: () => {

        },
      });
      return false;
    }
    if (this.data.namee == '' || this.data.phonenum == '') {
      my.showToast({
        type: 'fail',
        content: '请点击添加联系人',
        duration: 3000,
        success: () => {

        },
      });
      return false;
    }
    if (this.data.seleted == '') {
      my.showToast({
        type: 'fail',
        content: '请选择紧急联系人关系',
        duration: 3000,
        success: () => {

        },
      });
      return false;
    }

    console.log("8888888888888888888888888888888", app.globalData.userlocation)
    if (app.globalData.userlocation == 'null' || app.globalData.userlocation == '用户拒绝访问当前地址') {
      // 获当前地址
      app.getLocation()
      return false;
    }
    if (this.data.haveTogetherPerson == '1') {
      if (this.data.rentPersonIds.length < 1) {
        my.showToast({
          type: 'fail',
          content: '请选择共租人信息！',
          duration: 3000,
          success: () => {

          },
        });
        return false;
      }
    }
    if (!this.data.checked) {
      my.showToast({
        type: 'fail',
        content: '请阅读并同意《租赁服务协议》与《其他服务协议》',
        duration: 3000,
        success: () => {

        },
      });
      return false;
    }


    // 订单数据详细数据
    const data = Object.assign({},
      // this.accectData,
      {
        // 商品基础数据
        rentPersonIds: this.data.rentPersonIds,
        extraInfo: this.data.extraInfo,
        title: this.data.msg,
        id: this.data.id,
        model: {
          price: this.data.money * this.data.zlnum,
          leaseTerm: this.data.trem_value,
        },
        deposit: this.data.cash * this.data.zlnum,
        outPrice: this.data.outPrice * this.data.zlnum,
        worryMoney: this.data.worryMoney * this.data.zlnum,
        buyOutPrice: this.data.buyOut * this.data.zlnum,
        image: this.data.image,
        detail: this.data.detail,
        smash: this.data.smash.value * this.data.zlnum,
        productType: this.data.productType,
        firstPayPeriod: this.data.firstPayPeriod, // 首付期数
        cashPeriod: this.data.cashPeriod, // 押金期数
        vinno: this.data.vinno
      }
    );
    const getStorageData = function (arg, key) {
      const storageData = my.getStorageSync({
        key: arg
      }).data;
      return storageData != null && storageData ? storageData[key] : undefined
    }
    let params = {
      promotionAccount: getStorageData('promotionAccount', "promotionAccount"),
      flowState: getStorageData('promotionAccount', "flowState"),
      isAgreement: 0,
      agreementNo: null,
      linkPersonName: this.data.namee,
      linkPersonRelations: this.data.seleted,
      linkPersonMobile: this.data.phonenum,
      params: JSON.stringify(data),
      puid: my.getStorageSync({
        key: 'puid'
      }).data != null ? my.getStorageSync({
        key: 'puid'
      }).data : '',
      tit: this.data.tit,
      province: this.data.province,
      city: this.data.city,
      num: this.data.zlnum,
      district: this.data.district,
      street: this.data.street,
      address: this.data.address,
      phone: this.data.phone,
      email: this.data.email,
      couponUserId: this.data.chooseid,
      invoice: this.data.invoice,
      cont: this.data.cont,
      sid: this.data.sid,

      orderAuthCode: this.data.formId,
      currentAddress: app.globalData.userlocation
    }

    app.order.save(params)
      .then(json => {

        console.log("--------7777--", json)
        if (json.code != 200) {
          my.alert({
            content: json.msg
          });
          return
        } else if (json.code == 200) {
          this.setData({
            orderId: json.data
          })
          // if (this.data.types == '2') {
          //   this.onpay()
          // } else {
          app.order.freeze(json.data)
            .then(pay => {
              //console.log("=================================", pay
              my.tradePay({
                orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
                success: (res) => {
                  console.log("=================>>>>>>>支付", res)
                  if (res.resultCode == 9000) {
                    my.alert({
                      content: "支付成功",
                    });
                    // this.couponsucess()
                    // this.paysucess()
                    let clikid = my.getStorageSync({
                      key: 'promotionAccount'
                    }).data ? my.getStorageSync({
                      key: 'promotionAccount'
                    }).data.clickid : null
                    console.log("clikid", clikid)
                    if (clikid != null) {
                      this.ttdata()
                    } else {
                      my.removeStorage({
                        key: 'promotionAccount',
                        success: function () {
                          console.log('缓存删除成功');


                        }
                      });
                    }


                    setTimeout(() => {
                      my.reLaunch({
                        url: "/pages/order/renzheng/renzheng?id=" + json.data
                      });
                    }, 500)

                  } else {
                    let e = {}
                    e.orderId = this.data.orderId;
                    e.userId = my.getStorageSync({
                      key: 'user'
                    }).data.zfbUserId;
                    app.other.merchant(e).then(res => {
                      console.log("返回消息", res)
                    }).finally(() => {
                      setTimeout(() => {
                        my.navigateTo({
                          url: "/pages/order/orderList/orderList"
                        });
                      }, 500)
                    })
                  }
                },
              });
            })
          // }

        }


      }).catch(e => {
        console.log("222", e)

        my.showToast({
          content: e.msg ? e.msg : '网络异常'
        });
      })

  },
  yhj_list() {
    my.navigateTo({
      url: '/pages/order/coupons/coupons?ids=' + this.data.shopids + "&page=" + 1
    });
  },
  ttdata() {
    my.request({
      url: 'https://analytics.oceanengine.com/api/v2/conversion',
      method: 'POST',
      data: {
        event_type: 'shopping',
        context: {
          ad: {
            callback: my.getStorageSync({
              key: 'promotionAccount'
            }).data.clickid,
            match_type: 1
          },
          timestamp: new Date().getTime()
        },
      },
      headers: {
        'content-type': 'application/json', //默认值
      },
      dataType: 'json',
      success: function (res) {
        console.log("執行cg", res)
        if (res.data.code == '0') {
          my.removeStorage({
            key: 'promotionAccount',
            success: function () {
              console.log('缓存删除成功');
            }
          });
        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        my.hideLoading();

      },
    });


  },
  couponsucess() {

    let that = this;
    let e = {}
    e.id = that.data.chooseid;
    e.status = 1
    app.order.couponedit(e)
      .then(res => {


      })

  },
  // paysucess() {
  //   let that = this;
  //   let e = {}
  //   e.orderId = that.data.orderId;
  //   app.sell.paysuccess(e)
  //     .then(res => {

  //       console.log("支付成功分销接口", res)
  //       if (res.code == '0') {

  //       }

  //     })
  // },
  onpay() {
    let that = this;
    let e = {}
    e.subject = '无忧保障支付';
    e.type = '2';
    e.uid = my.getStorageSync({
      key: 'user'
    }).data.id;
    e.orderMoney = that.data.worryMoney / 100;
    app.order.ordervip(e)
      .then(res => {
        console.log("返回消息", res)
        let infor = res.data.data;
        infor.status = 1;
        console.log("!!!!!!", infor)
        that.setData({
          infor: infor
        })
        my.tradePay({
          tradeNO: res.data.data.tradeNo,
          success: function (res) {
            console.log(res)
            if (res.resultCode == 9000) {
              that.editordervip(res.extendInfo)

              my.alert({
                content: "支付成功",
              });

            } else {
              let e = {}
              e.orderId = that.data.orderId;
              e.userId = my.getStorageSync({
                key: 'user'
              }).data.zfbUserId;
              // app.other.merchant(e)
              //   .then(res => {
              //     console.log("返回消息", res)
              //     if (res.code == '0') {
              //       setTimeout(() => {
              //         my.navigateTo({
              //           url: "/pages/order/orderList/orderList"
              //         });
              //       }, 500)
              //     }
              //   })
            }
          },

        });
      })
  },
  editordervip(e) {
    let that = this;
    console.log("56565", e)
    let res = JSON.stringify(e);
    let infors = that.data.infor;
    infors.body = res;
    infors.orderId = that.data.orderId;
    setTimeout(() => {
      my.reLaunch({
        url: "/pages/order/renzheng/renzheng?id=" + that.data.orderId
      });
    }, 500)
    // app.order.editordervip(infors)
    //   .then(res => {
    //     if (res.code == '0') {
    //       setTimeout(() => {
    //         my.reLaunch({
    //           url: "/pages/order/renzheng/renzheng?id=" + that.data.orderId
    //         });
    //       }, 500)
    //     }
    //     console.log("返回消息", res)
    //   })
  },
  // 跳转
  navigateTo(e) {
    // //console.log(e)
    app.navigateTo(e)
  }


});